package com.xinlong.shop.api.order;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.xinlong.shop.api.common.BuyerBaseController;
import com.xinlong.shop.core.logistics.LogisticsPluginFactory;
import com.xinlong.shop.core.logistics.entity.LogisticsTraces;
import com.xinlong.shop.core.member.service.IMemberService;
import com.xinlong.shop.core.order.OrderQueryParam;
import com.xinlong.shop.core.order.OrderStatusEnum;
import com.xinlong.shop.core.order.entity.Order;
import com.xinlong.shop.core.order.entity.dto.CreateOrderDTO;
import com.xinlong.shop.core.order.entity.vo.OrderVO;
import com.xinlong.shop.core.order.service.IOrderService;
import com.xinlong.shop.core.site.entity.Logistics;
import com.xinlong.shop.core.site.service.ILogisticsService;
import com.xinlong.shop.framework.common.R;
import com.xinlong.shop.framework.core.entity.Member;
import com.xinlong.shop.framework.security.constant.SecurityConstants;
import com.xinlong.shop.framework.security.util.TokenUtil;
import com.xinlong.shop.framework.service.ISysSettingService;
import com.xinlong.shop.framework.weixin.service.WeiXinMpService;
import io.swagger.annotations.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Sylow
 * @Description 买家订单API
 * @Date: Created in 15:13 2023/7/4
 */
@Api(tags = "买家订单API")
@Validated      // get请求验证参数时需要
@RestController
@RequestMapping("/buyer/order/order")
public class BuyerOrderController extends BuyerBaseController {

    private final IOrderService orderService;
    private final ISysSettingService sysSettingService;
    private final WeiXinMpService weiXinMpService;
    private final LogisticsPluginFactory logisticsPluginFactory;
    private final ILogisticsService logisticsService;

    public BuyerOrderController(IOrderService orderService, IMemberService memberService, TokenUtil tokenUtil, ISysSettingService sysSettingService, WeiXinMpService weiXinMpService, LogisticsPluginFactory logisticsPluginFactory, ILogisticsService logisticsService) {
        super(memberService, tokenUtil);
        this.orderService = orderService;
        this.sysSettingService = sysSettingService;
        this.weiXinMpService = weiXinMpService;
        this.logisticsPluginFactory = logisticsPluginFactory;
        this.logisticsService = logisticsService;
    }

    @ApiOperation(value = "创建订单")
    @ApiResponses(@ApiResponse(code = 200, message = "操作成功", response = Order.class))
    @RequestMapping(value = "/create-order", method = RequestMethod.POST, produces = "application/json")
    public R createOrder(String code, String openid, @RequestBody CreateOrderDTO createOrderDTO, @RequestHeader(value = SecurityConstants.TOKEN_HEADER, required = true) String token){

        // 验证用户是否存在
        Member member = getMember(token);
        if (member == null) {
            return R.error("用户不存在");
        }

        Map<String, Object> result = new HashMap<>();

        if (StrUtil.isBlank(openid)) {
            openid = weiXinMpService.getOpenId(code);
            if (StrUtil.isBlank(openid)) {
                return R.error("操作失败，请重试");
            }
        }
        createOrderDTO.setMemberId(member.getId());
        createOrderDTO.setMemberName(member.getMemberName());
        Order order = this.orderService.createOrder(createOrderDTO);

        PrepayWithRequestPaymentResponse response = weiXinMpService.mpPay(order.getOrderSn(), openid,
                order.getOrderPrice(), "商城-订单：" + order.getOrderSn());

        result.put("response", response);
        result.put("openid", openid);   // 返回前端做缓存，暂时不保存到后端

        return R.success(result);
    }

    @ApiOperation(value = "订单列表页的支付, 不做用户筛选谁都可以支付，以后可做代付")
    @ApiResponses(@ApiResponse(code = 200, message = "操作成功"))
    @RequestMapping(value = "/order-pay", method = RequestMethod.POST, produces = "application/json")
    public R orderPay(String code, String openid, String orderSn){
        if (orderSn == null) {
            return R.error();
        }
        Order order = this.orderService.findByOrderSn(orderSn);
        if (order == null) {
            return R.error("订单不存在");
        }
        if (order.getOrderStatus() != OrderStatusEnum.CREATE.getCode()) {
            return R.error("订单已支付");
        }
        Map<String, Object> result = new HashMap<>();
        if (StrUtil.isBlank(openid)) {
            openid = weiXinMpService.getOpenId(code);
            if (StrUtil.isBlank(openid)) {
                return R.error("操作失败，请重试");
            }
        }
        PrepayWithRequestPaymentResponse response = weiXinMpService.mpPay(order.getOrderSn(), openid,
                order.getOrderPrice(), "商城-订单：" + order.getOrderSn());

        result.put("response", response);
        result.put("openid", openid);   // 返回前端做缓存，暂时不保存到后端

        return R.success(result);
    }

    @ApiOperation(value = "订单列表")
    @ApiResponses(@ApiResponse(code = 200, message = "操作成功", response = OrderVO.class))
    @RequestMapping(value = "", method = RequestMethod.GET, produces = "application/json")
    public R orderList(Integer current, String status, @RequestHeader(value = SecurityConstants.TOKEN_HEADER, required = true) String token) {
        Integer statusIndex = null;
        if ("paid_off".equals(status)) {
            statusIndex = OrderStatusEnum.PAID_OFF.getCode();
        } else if("shipped".equals(status)) {
            statusIndex = OrderStatusEnum.SHIPPED.getCode();
        } else if("complete".equals(status)) {
            // 暂时没有评论 所以说 这里的已完成 就是确认收货待评价
            statusIndex = OrderStatusEnum.ROG.getCode();
        } else if("create".equals(status)) {
            //
            statusIndex = OrderStatusEnum.CREATE.getCode();
        }
        Member member = getMember(token);
        OrderQueryParam orderQueryParam = new OrderQueryParam();
        orderQueryParam.setOrderStatus(statusIndex);
        orderQueryParam.setMemberId(member.getId());
        IPage<OrderVO> page = new Page<>(current, 10);
        page = this.orderService.selectPageOrderVo(page, orderQueryParam);
        return R.success("操作成功", page);
    }

    @ApiOperation(value = "查询物流信息")
    @ApiResponses(@ApiResponse(code = 200, message = "操作成功"))
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单id", required = true, paramType = "query")
    })
    @RequestMapping(value = "/query-logistics", method = RequestMethod.GET, produces = "application/json")
    public R queryLogistics(@NotNull(message = "订单id不能为空")Integer id, @RequestHeader(value = SecurityConstants.TOKEN_HEADER, required = true) String token) {
        if(id.equals(0)) {
            return R.error("订单id不能为空");
        }
        Order order = this.orderService.getById(id);
        if (order == null) {
            return R.error("订单不存在");
        }
        // 判断是否属于自己的订单
        Member member = getMember(token);
        if (!order.getMemberId().equals(member.getId())) {
            return R.error("订单不存在");
        }
        // 查询物流信息
        Logistics logistics = logisticsService.getById(order.getLogisticsId());
        LogisticsTraces logisticsTraces = logisticsPluginFactory.currentPlugin().instantQuery(logistics, order.getLogisticsSn(), order.getShipMobile());
        return R.success(logisticsTraces);
    }

    @ApiOperation(value = "买家确认收货")
    @ApiResponses(@ApiResponse(code = 200, message = "操作成功"))
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单id", required = true, paramType = "path")
    })
    @RequestMapping(value = "/confirm-receipt/{id}", method = RequestMethod.PUT, produces = "application/json")
    public R confirmReceipt(@PathVariable("id") Integer id, @RequestHeader(value = SecurityConstants.TOKEN_HEADER, required = true) String token) {
        if(id.equals(0)) {
            return R.error("订单id不能为空");
        }
        Order order = this.orderService.getById(id);
        if (order == null) {
            return R.error("订单不存在");
        }
        // 判断是否属于自己的订单
        Member member = getMember(token);
        if (!order.getMemberId().equals(member.getId())) {
            return R.error("订单不存在");
        }
        // 判断订单状态
        if (!order.getOrderStatus().equals(OrderStatusEnum.SHIPPED.getCode())) {
            return R.error("订单状态不正确");
        }
        this.orderService.updateOrderStatus(order.getId(), OrderStatusEnum.ROG.getCode());

        return R.success();
    }

}
